/*
 * Futbol.java
 *
 * Created on 16 de julio de 2006, 0:08
 */

package futbol;

import futbol.iu.PintarCampo;
import futbol.iu.PintarMenu;
import futbol.iu.PintarRotulos;
import futbol.tacticas.ComandoIrA;
import futbol.tacticas.concursantes.Tactica;
import futbol.tacticas.concursantes.Concursantes;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import javax.swing.JFileChooser;
import resource.LoadResource;
import java.awt.*;

/**
 *
 * @author  Administrador
 */
public class Futbol extends javax.swing.JFrame implements Runnable{
    
    private BufferedImage db=new BufferedImage(600,400,BufferedImage.TYPE_4BYTE_ABGR);

    private Image campo;
    
    private int dx=300, dy=210;
    private Thread hilo=new Thread(this);
    private Partido partido=null;
    private PintarRotulos pe=null; //Dibuja los rayos.
    private PintarCampo pc=null;  //
    private PintarMenu pm=new PintarMenu(this);
    private String nombres[]=new String[2];
    private Font font;
    private boolean showChampions=false;
    
    
    //Visualiza el estado
    
    private void pulsarTecla(int pulsaTecla){
        if (pm!=null){
            switch(pulsaTecla){
                case KeyEvent.VK_PAGE_UP:
                    pm.desplazar(-5);
                    repaint();
                    break;
                case KeyEvent.VK_PAGE_DOWN:
                    pm.desplazar(5);
                    repaint();
                    break;
                case KeyEvent.VK_UP:
                    pm.desplazar(-1);
                    repaint();
                    break;
                case KeyEvent.VK_DOWN:
                    pm.desplazar(1);
                    repaint();
                    break;
                case KeyEvent.VK_1:
                    showChampions=true;
                    repaint();
                    break;
                case KeyEvent.VK_ESCAPE:
                    showChampions=false;
                    repaint();
                    break;
                    
                case KeyEvent.VK_ENTER:
                case KeyEvent.VK_SPACE:
                    int nSel[]=pm.seleccionaEquipo();
                    if (nSel!=null){
                        partido=new Partido(Concursantes.getTodasLasTacticas()[nSel[0]], Concursantes.getTodasLasTacticas()[nSel[1]]);
                    }
                    repaint();
                    break;
                case KeyEvent.VK_C:
                    //Carga el fichero
                    JFileChooser jf=new JFileChooser();
                    jf.setFileFilter(new javax.swing.filechooser.FileFilter() {
                        public boolean accept(File f) {
                            try{
                                if (f.isDirectory()) return true;
                                String s=f.getCanonicalPath();
                                if (s.length()<4) return false;
                                if (s.substring(s.length()-4,s.length()).toLowerCase().equals(".jvc"))
                                    return true;
                            } catch(Exception exception){
                                return false;
                            }
                            return false;
                        }
                        public String getDescription() {
                            return "Partido grabado JavaCup v1.2";
                        }
                    });
                    int returnVal=jf.showOpenDialog(this);
                    if (returnVal == JFileChooser.APPROVE_OPTION){
                        partido = new Partido(jf.getSelectedFile().toString());
                    }
                    break;
                }
            }
            if (pc!=null){
                switch(pulsaTecla){
                    case KeyEvent.VK_ESCAPE: 
                        partido=null;
                        pc=null;
                        showChampions=false;
                }
            }
    }
    
    /** Creates new form Futbol */
    public Futbol() {
        try{
            campo=LoadResource.getDefault().getCampo();
            setIconImage(LoadResource.getDefault().getIcono());
            
            MediaTracker tracker = new MediaTracker(this) ;
            tracker.addImage(campo, 1) ;
            tracker.waitForAll() ;
            
            this.addKeyListener(
                new KeyAdapter() {
                    public void keyPressed(KeyEvent e) {
                        pulsarTecla(e.getKeyCode());
                    }
            });
        }catch(Exception e){
        }
        initComponents();
        hilo.start();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Torneo de futbol virtual");
        setResizable(false);
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 565, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 366, Short.MAX_VALUE)
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-573)/2, (screenSize.height-400)/2, 573, 400);
    }// </editor-fold>//GEN-END:initComponents

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
// TODO add your handling code here:
        if (pc!=null){
            pc.setAux(evt.getX()-dx, evt.getY()-dy);
        }
    }//GEN-LAST:event_formMouseMoved
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Futbol().setVisible(true);
            }
        });
    }
    
    public void paint(Graphics g){
        Graphics gdb=db.getGraphics();
        if (font==null)
            font=new Font("ARIAL", Font.BOLD, 15);
        gdb.setFont(font);
        if (partido==null){
            if (pm==null) 
                pm=new PintarMenu(this, showChampions);
            pm.setShowChampions(showChampions);
            pm.pintar(gdb);
        }else if (partido!=null){
            pm=null;
            if (pe!=null){
                pe.paint(gdb, this);  //Dibuja los rayos
            }
            else if (pc!=null)
            {
                gdb.setColor(Color.white);
                gdb.drawImage(campo, 0, 0, this);
                pc.pintar(gdb);
            }
        }
        g.drawImage(db,0,0,this);
    }
    
    public void run(){
        try {
            while (true){
                Thread.sleep(300);
                if (partido!=null){
                    pm=null; //Quita el menu
                    LoadResource.getDefault().playSoundRayos();
                    Tactica t1=partido.getTactica(0);
                    Tactica t2=partido.getTactica(1);
                    pe=new PintarRotulos(t1.getNombre(), t1.getColor1(), t1.getColor2(),
                                        t2.getNombre(), t2.getColor1(), t2.getColor2());
                    
                    //************************************************
                    //          Mostrar presentacion.
                    //************************************************
                    for (int n=0;n<300;n++){
                        pe.mover();
                        repaint();
                        Thread.sleep(10);
                    }
                    
                    pe=null;
                    
                    pc=new PintarCampo(partido);
                    repaint();
                    //************************************************
                    //          Ejecuta el partido.
                    //************************************************
                    if (Concursantes.MODO_VISUALIZAR) Thread.sleep(6000);
                    for (int time=0;time<1800 && pc!=null && partido!=null;time++){
                        try{
                            if (time==0) LoadResource.getDefault().playSoundSilbato();
                            if (Concursantes.MODO_VISUALIZAR) Thread.sleep(100);
                            if (time<1800){
                                partido.mover();
                                if (partido.getBola().getGolpeada()==1)
                                    LoadResource.getDefault().playSoundKit();
                                repaint();
                                
                                int huboGol=partido.getUltimaJugadaHuboGol();
                                if (huboGol!=-1 && Concursantes.MODO_VISUALIZAR){
                                    General.indicarGol() ;
                                    pc.resaltaMarcador(this.getGraphics(), huboGol) ;
                                    repaint();
                                    General.indicarSaqueDeCentro();
                                }
                                pc.setTime(time);
                            }
                        }catch(Exception e3){
                        }
                        repaint();
                    }
                    
                    if (pc!=null && Concursantes.MODO_VISUALIZAR) {
                        LoadResource.getDefault().playSoundSilbato();
                        pc.setTime(1800); repaint();  //Visualiza el ganador
                        Thread.sleep(6000);
                    }
                    partido=null;  //Marcamos el partido a null para que no visualice nada ms
                    pc=null;
                    pm=new PintarMenu(this, showChampions);
                    repaint();
                }
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    
    public boolean getShowChampions(){
        return showChampions;
    }
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    
}
